package com.coffee.filter;

import com.alibaba.fastjson.JSONObject;
import com.coffee.common.BaseContext;
import com.coffee.entity.R;
import com.coffee.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] uris = {
                "/user/register",
                "/user/login",
                "/user/loginout"
        };
        for (String uri : uris) {
            if (MATCHER.match(uri, requestURI)) {
                filterChain.doFilter(request,response);
                return;
            }
        }
        //校验 token
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){ //如果没有JWT令牌
            System.out.println("获取到token为空 , 返回错误信息...");
            String result = JSONObject.toJSONString(R.error("NOT_LOGIN"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(result);
            return ;
        }

        //解析jwt令牌, 如果解析失败, 则说明令牌无效 , 返回 未登录 提示信息
        try {
            //令牌解析成功, 直接放行
            Claims claims = JwtUtils.parseJWT(token);
            BaseContext.set(claims.get("id").toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("令牌解析失败 , 返回错误信息...");
            ObjectMapper objectMapper = new ObjectMapper();
            String result = JSONObject.toJSONString(R.error("NOT_LOGIN"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(result);
            return ;
        }
        //如果校验通过放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
